/**
 * Copyright (C), 2001-2031, www.bosssof.com.cn
 * FileName: TestController.java
 * Author: YuXingZh
 * Date: 15/6/2024 上午9:15
 * Description:
 * 测试
 * History:
 * Date          Author   Version  Desc
 * 2024-01-01    bosssoft  1.0.0   initialize this file
 */
package com.bosssoft.g1.gateway.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.bosssoft.g1.common.data.vo.CommonResponse;
import com.bosssoft.g1.common.util.CommonResponseUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * @className: TestController
 * @description: 解决什么问题：
 * 演示线程池的正确使用
 * 主要方法和数据成员：
 * methodxx 使用 ThreadPoolExecutor创建线程进行任务操作
 * 注意事项：
 * 例如：该类需要从容器获取不可以new
 * @author: YuXingZh
 * @date: 15/6/2024上午9:15
 * @since 1.0
 **/
@RestController
public class TestController {

    @GetMapping("/test")
    @SentinelResource(value = "GLOBAL_LIMIT_RESOURCE", blockHandler = "handleException")
    public CommonResponse<String> test() {
        System.out.println("正常访问");
        return CommonResponseUtils.success("test");
    }

    public CommonResponse<String> handleException(BlockException ex) {
        System.out.println("限流");
        return CommonResponseUtils.failed("限流中");
    }

    @GetMapping("/test2")
    public CommonResponse<String> test2() {
        return CommonResponseUtils.success("{'res':'Test2!'}");
    }

    @GetMapping("/test3")
    @SentinelResource(value = "GLOBAL_CIRCUIT_BREAKER", blockHandler = "handleBlock1")
    public CommonResponse<String> test3() {
        Random random = new Random();
        boolean triggerError = random.nextBoolean();
        if (triggerError) {
            System.out.println("触发熔断");
            throw new RuntimeException("自定义异常");
        }
        return CommonResponseUtils.success("Hello, Sentinel!");
    }

    public CommonResponse<String> handleBlock(BlockException ex) {
        return CommonResponseUtils.failed("Blocked by Sentinel: " + ex.getClass().getSimpleName());
    }

    public CommonResponse<String> handleBlock1(BlockException ex) {
        System.out.println("熔断");
        return CommonResponseUtils.failed("熔断 by Sentinel: " + ex.getClass().getSimpleName());
    }
}